{% extends "base.html" %}

{% block title %}选课中心 - 学生选课系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="fas fa-tasks me-2"></i>选课中心</h2>
    <div>
        <a href="/my-courses" class="btn btn-outline-primary">
            <i class="fas fa-list me-1"></i>我的课程
        </a>
    </div>
</div>

<!-- 学生信息 -->
<div class="card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">学生信息</h5>
    </div>
    <div class="card-body">
        <!-- 学生选择器容器（管理员使用） -->
        <div id="studentSelectorContainer"></div>
        
        <div class="row">
            <div class="col-md-12">
                <div id="studentInfo" class="text-muted">
                    正在加载学生信息...
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 课程列表 -->
<div class="card">
    <div class="card-header">
        <h5 class="card-title mb-0">可选课程</h5>
    </div>
    <div class="card-body">
        <div id="coursesList">
            <div class="text-center text-muted py-4">
                <i class="fas fa-spinner fa-spin fa-2x mb-2"></i>
                <p>正在加载课程信息...</p>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
// 页面加载时自动加载当前学生信息和课程
document.addEventListener('DOMContentLoaded', function() {
    // 如果是管理员，先加载学生选择器
    const userType = '{{ session.get("user_type", "") }}';
    if (userType === 'admin') {
        loadStudentSelector().then(() => {
            loadCurrentStudentInfo();
            loadAvailableCourses();
        });
    } else {
        // 学生用户只能看到自己的信息
        loadCurrentStudentInfo();
        loadAvailableCourses();
    }
});

// 加载学生选择器（管理员使用）
async function loadStudentSelector() {
    try {
        const response = await fetch('/api/students');
        if (!response.ok) {
            throw new Error('获取学生列表失败');
        }
        const students = await response.json();
        
        if (students.length > 0) {
            const selectorContainer = document.getElementById('studentSelectorContainer');
            const selectorHtml = `
                <div class="row mb-3">
                    <div class="col-md-6">
                        <label for="studentSelector" class="form-label"><strong>选择学生:</strong></label>
                        <select id="studentSelector" class="form-select" onchange="onStudentChange()">
                            ${students.map(student => 
                                `<option value="${student._id}">${student.name} (${student.phone || '无电话'})</option>`
                            ).join('')}
                        </select>
                    </div>
                </div>
            `;
            selectorContainer.innerHTML = selectorHtml;
        }
    } catch (error) {
        console.error('加载学生选择器失败:', error);
    }
}

// 学生选择变化时的处理
async function onStudentChange() {
    await loadCurrentStudentInfo();
    await loadAvailableCourses();
}

// 获取当前学生ID（从session或API获取）
async function getCurrentStudentId() {
    const userType = '{{ session.get("user_type", "") }}';
    const userId = '{{ session.get("user_id", "") }}';
    
    // 如果是学生，需要从认证信息获取对应的学生ID
    if (userType === 'student') {
        try {
            const response = await fetch('/api/student-auth-info');
            if (response.ok) {
                const authInfo = await response.json();
                return authInfo.student_id;
            }
        } catch (error) {
            console.error('获取学生认证信息失败:', error);
        }
        return null;
    }
    
    // 如果是管理员，返回当前选择的学生ID（默认为第一个学生）
    const selectedStudentId = document.getElementById('studentSelector')?.value;
    if (selectedStudentId) {
        return selectedStudentId;
    }
    
    // 如果没有选择学生，尝试获取第一个学生
    try {
        const response = await fetch('/api/students');
        if (response.ok) {
            const students = await response.json();
            if (students.length > 0) {
                return students[0]._id;
            }
        }
    } catch (error) {
        console.error('获取学生列表失败:', error);
    }
    
    return null;
}

// 获取当前学生姓名
async function getCurrentStudentName() {
    const userType = '{{ session.get("user_type", "") }}';
    
    // 如果是学生，从session获取姓名
    if (userType === 'student') {
        return '{{ session.get("name", "学生") }}';
    }
    
    // 如果是管理员，从选择器获取学生姓名
    const studentSelector = document.getElementById('studentSelector');
    if (studentSelector) {
        const selectedOption = studentSelector.options[studentSelector.selectedIndex];
        return selectedOption ? selectedOption.text : '学生';
    }
    
    return '学生';
}

// 加载当前学生信息
async function loadCurrentStudentInfo() {
    const studentId = await getCurrentStudentId();
    if (!studentId) {
        document.getElementById('studentInfo').innerHTML = '未找到学生信息，请重新登录';
        return;
    }

    try {
        const response = await fetch(`/api/students/${studentId}`);
        if (!response.ok) {
            throw new Error('获取学生信息失败');
        }
        const student = await response.json();
        renderStudentInfo(student);
    } catch (error) {
        console.error('加载学生信息失败:', error);
        document.getElementById('studentInfo').innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                加载学生信息失败: ${error.message}
            </div>
        `;
    }
}

// 渲染学生信息
function renderStudentInfo(student) {
    const infoDiv = document.getElementById('studentInfo');
    infoDiv.innerHTML = `
        <div class="row">
            <div class="col-md-6">
                <strong>姓名:</strong> ${student.name || '未设置'}<br>
                <strong>学号:</strong> ${student.student_id || '未设置'}<br>
                <strong>年级:</strong> ${student.grade || '未设置'}<br>
                <strong>专业:</strong> ${student.major || '未设置'}
            </div>
            <div class="col-md-6">
                <strong>邮箱:</strong> ${student.email || '未设置'}<br>
                <strong>电话:</strong> ${student.phone || '未设置'}<br>
                <strong>已选课程数:</strong> <span id="selectedCount">加载中...</span>
            </div>
        </div>
    `;
    
    // 加载学生已选课程数量
    loadStudentCoursesCount(student._id);
}

// 加载学生已选课程数量
async function loadStudentCoursesCount(studentId) {
    try {
        const response = await fetch(`/api/student-courses/${studentId}`);
        if (response.ok) {
            const courses = await response.json();
            document.getElementById('selectedCount').textContent = courses.length;
        } else {
            document.getElementById('selectedCount').textContent = '未知';
        }
    } catch (error) {
        console.error('加载已选课程数量失败:', error);
        document.getElementById('selectedCount').textContent = '未知';
    }
}

// 加载可选课程
async function loadAvailableCourses() {
    const studentId = await getCurrentStudentId();
    if (!studentId) {
        document.getElementById('coursesList').innerHTML = `
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-triangle me-2"></i>
                请先登录学生账号
            </div>
        `;
        return;
    }

    try {
        // 先获取所有课程
        const coursesResponse = await fetch('/api/courses');
        if (!coursesResponse.ok) {
            throw new Error('获取课程列表失败');
        }
        const allCourses = await coursesResponse.json();
        
        // 获取学生已选课程
        const selectedResponse = await fetch(`/api/student-courses/${studentId}`);
        const selectedCourses = selectedResponse.ok ? await selectedResponse.json() : [];
        
        // 过滤出未选的课程
        const selectedCourseIds = selectedCourses.map(course => course.course_id);
        const availableCourses = allCourses.filter(course => 
            !selectedCourseIds.includes(course._id)
        );
        
        renderAvailableCourses(availableCourses, studentId);
    } catch (error) {
        console.error('加载可选课程失败:', error);
        document.getElementById('coursesList').innerHTML = `
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                加载可选课程失败: ${error.message}
            </div>
        `;
    }
}

// 渲染可选课程
function renderAvailableCourses(courses, studentId) {
    const coursesList = document.getElementById('coursesList');
    
    if (courses.length === 0) {
        coursesList.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fas fa-graduation-cap fa-2x mb-2"></i>
                <p>暂无可选课程或已选择所有课程</p>
            </div>
        `;
        return;
    }
    
    coursesList.innerHTML = courses.map(course => `
        <div class="card mb-3">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <h5 class="card-title">${course.course_name} (${course.course_code || '无编号'})</h5>
                        <p class="card-text">
                            <strong>学分:</strong> ${course.credits || 0} 学分<br>
                            <strong>授课教师:</strong> ${course.teacher || '未设置'}<br>
                            <strong>上课时间:</strong> ${course.schedule || '未设置'}<br>
                            <strong>上课地点:</strong> ${course.location || '未设置'}<br>
                            <strong>容量:</strong> ${course.capacity > 0 ? `${course.enrolled || 0}/${course.capacity}` : '无限制'}
                        </p>
                        ${course.description ? `<p class="card-text"><small>${course.description}</small></p>` : ''}
                    </div>
                    <div class="col-md-4 text-end">
                        <button class="btn btn-primary" onclick="selectCourse('${studentId}', '${course._id}', '${course.course_name}')">
                            <i class="fas fa-plus me-1"></i>选择课程
                        </button>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// 选择课程
async function selectCourse(studentId, courseId, courseName) {
    if (!confirm(`确定要选择课程 "${courseName}" 吗？`)) {
        return;
    }
    
    try {
        const response = await fetch('/api/selection', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                student_id: studentId,
                course_id: courseId
            })
        });
        
        if (response.ok) {
            const result = await response.json();
            alert('选课成功！');
            // 重新加载可选课程和已选课程数量
            await loadAvailableCourses();
            await loadStudentCoursesCount(studentId);
        } else {
            const error = await response.json();
            throw new Error(error.error || '选课失败');
        }
    } catch (error) {
        console.error('选课失败:', error);
        alert('选课失败: ' + error.message);
    }
}
</script>
{% endblock %}
